<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


/* 关于返回结果的json格式建议如下：
data:执行成功返回的数据
status:简单的表示业务执行的状态，如成功success，登录失败，更新失败等
code:业务执行状态的代码（可不设计）
message:表示详细信息
version:版本号 
*/


class Task extends CI_Controller
{

	var $_login_userid;

	function __construct()
	{
		parent::__construct();
		//$this->_login_userid=0;
		$this->_login_userid = $this->get_login_userid();
		$this->load->database();
	}

	//获得当前登录的用户id
	private function get_login_userid()
	{
		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');
		if ($this->tank_auth->is_logged_in()) {
			return $this->tank_auth->get_user_id();
		} else {
			return 0;
		}
	}
	//检测当前登录用户是否是某个团队的成员
	private function check_is_member($teamid)
	{
		$this->load->database();
		$this->db->where('tid', $teamid);
		$query = $this->db->get('team_user');
		if ($num_rows = $query->num_rows() > 0) {
			return true;
		} else {
			return false;
		}
	}
	//将数组转换成json，并输出
	private function array_to_json($array)
	{
		$json_string = json_encode($array);
		echo $json_string;
	}

	//按给定的sql查询并输出json
	private function query_to_json($sql)
	{
		if ($sql) {
		} else { //防止出现空查询条件
			$sql = "select 1 ";
		}
		$this->load->database();
		$query = $this->db->query($sql);
		if (($num_rows = $query->num_rows()) > 0) {
			$result_array = array(
				'data' => $query->result_array(),
				'status' => 'success',
				'message' => '查询到' . $num_rows . "条记录"
			);
		} else {
			$result_array = array(
				'status' => 'nofound',
				'message' => '消息' . $this->db->last_query()
			);
		}
		$this->array_to_json($result_array);
	}

	//按给定的where子句生成查询task并输出
	private function query_by_where_to_json($where)
	{
		$this->load->database();
		if ($where) {
		} else { //防止出现空查询条件
			$where = " false ";
		}
		//		echo $where;		
		$this->db->where('uid', $this->_login_userid);
		$this->db->where($where, NULL, FALSE);
		$this->db->order_by('sort', 'desc');
		$query = $this->db->get('task');
		if ($num_rows = $query->num_rows() > 0) {
			$result_array = array(
				'data' => $query->result_array(),
				'status' => 'success',
				'message' => '查询到' . $num_rows . "条记录"
			);
		} else {
			$result_array = array(
				'status' => 'nofound',
				'message' => '消息' . $this->db->last_query()
			);
		}
		$this->array_to_json($result_array);
	}

	//取得任务（通用）
	public function gettask($where)
	{
		if (isset($_POST['team'])) {
			$this->get_team_task($_POST['team']);
			return;
		} else {
			$this->db->where('tid', NULL);
			$this->db->where('uid', $this->_login_userid);
		}
		$where = '1';
		query_by_where_to_json($where);
	}

	//取得当前用户的所有任务（不包括团队任务）
	public function getall($rand = 0, $workarea = 0)
	{

		// $result_array = array();
		// $this->load->database();

		if ($this->_login_userid) {
			$this->db->where('tid', NULL);
			$this->db->where('uid', $this->_login_userid);
		} else {
			$this->db->where('uid', 5);
		}

		if ($workarea || isset($_POST['workarea'])) {
			$this->db->where('areaid', $workarea);
		} else {
		}

		$this->db->where('archive !=', '1'); //默认只取得所有未归档的任务
		// $this->db->where('(nodetype IS NULL OR nodetype!="Z")'); //不取知识库的任务,注意要加括号，要加NULL
		$this->db->where('(nodetype IS NULL OR nodetype="")'); //只取nodetype类型为空的任务
		$this->db->order_by('sort desc,parent asc');

		$query = $this->db->get('task');
		if ($num_rows = $query->num_rows() > 0) {
			//$result_array['message']=$result_message;
			$result_array['data'] = $query->result_array();
			$result_array['status'] = 'success';
		} else {
			$result_array['status'] = 'nofound';
		}
		$this->array_to_json($result_array);
	}

	//取得某个团队的任务	
	public function get_team_task($teamid = 0, $rand = 0, $workarea = 0)
	{
		if (isset($_POST['team'])) {
			$teamid = $_POST['team'];
		}
		$sql = "select task.* from task,team,team_user where task.tid=team.id and team_user.tid=team.id AND team.id=" . $teamid . " AND team_user.uid=" . ($this->_login_userid ? $this->_login_userid : '5') . " order by in_date desc;";
		$this->query_to_json($sql);
	}

	//取得所有任务和所有团队任务，合并输出
	public function get_all_and_team($rand = 0, $workarea = 0)
	{
		$result_array = array();
		$r1 = array();
		$r2 = array();
		$this->load->database();
		if ($this->_login_userid) {
			$this->db->where('uid', $this->_login_userid);
		} else {
			$this->db->where('uid', 5);
		}
		if ($workarea) {
			$this->db->where('areaid', $workarea);
		} else {
		}

		//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
		$this->db->where('archive !=', '1'); //默认只取得所有未归档的任务
		$this->db->order_by('sort desc,parent asc');
		$query1 = $this->db->get('task');
		if ($num_rows = $query1->num_rows() > 0) {
			//			$result_array['message']=$result_message;
			$r1 = $query1->result_array();
			$result_array['status'] = 'success';
		} else {
			$result_array['status'] = 'nofound';
		}
		$query2 = $this->db->query("select task.* from task,team,team_user where task.tid=team.id and team_user.tid=team.id AND team_user.uid=" . ($this->_login_userid ? $this->_login_userid : '5') . " order by in_date desc;");
		if ($num_rows = $query2->num_rows() > 0) {
			$r2 = $query2->result_array();
		}
		$result_array['data'] = array_merge($r1, $r2);
		$this->array_to_json($result_array);
	}


	public function index()
	{
		$this->load->helper('url');
		$this->load->view('welcome_message');
	}

	// 插入任务
	public function insert()
	{

		//microtime(true)自 Unix 纪元(1970年)起精确到微秒的以秒为单位的当前时间
		// floor(microtime(true))取整成秒
		// 1,400,000,000，约2014-05-14 00:53:20的时间戳(秒)
		// 2的31次方=2,147,483,647，若以秒为单位，可存68年，若以0.1秒为粒度，只能存6年

		// $newnode_sort = floor((microtime(true) - 1400000000) * 10);
		$newnode_sort = floor((microtime(true) - 1400000000));

		$this->load->database();

		//			$sql = "INSERT INTO task (title, parent,areaid,sort,in_date,uid) 
		//			VALUES (".$this->db->escape($_REQUEST['title']).", ".$this->db->escape($_REQUEST['parent']).", ".$this->db->escape($_REQUEST['areaid']).",'".$newnode_sort."','".date("Y-m-d H:m:s")."','". $this->_login_userid."')";
		//			$this->db->query($sql);

		$data = array(
			'title' => $_REQUEST['title'],
			// 'parent' => $this->db->escape($_REQUEST['parent']),如果用escap的话，插入到表的字符串会被加上引号
			'parent' => $_REQUEST['parent'],
			'sort' => $newnode_sort,
			'in_date' => date("Y-m-d H:m:s"),
			'uid' => $this->_login_userid
		);
		if (isset($_POST['simple'])) {
			$data['simple'] = 1; //如果是来自简单任务视图
		}
		if (isset($_POST['active'])) {
			$data['active'] = 1; //如果是来自简单任务视图
		}
		if (isset($_POST['areaid'])) {
			// $data['areaid'] = $this->db->escape($_REQUEST['areaid']);
			$data['areaid'] = $_REQUEST['areaid'];
		}
		if (isset($_POST['team'])) {
			$data['tid'] = $_POST['team']; //如果是来自团队视图
		}
		$this->db->insert('task', $data);



		if ($this->db->affected_rows() > 0) {
			$status = 1;
			$newid = $this->db->insert_id();
			$sql = "call changeTaskParentAndParents(" . $newid . "," . $this->db->escape($_POST['parent']) . "," . $this->_login_userid . ");";
			$this->db->query($sql);
		} else {
			$status = 0;
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $this->db->last_query(),
			'data' => array(
				'newid' => $newid,
				'newnode_sort' => $newnode_sort
			)
		);

		if ($this->_login_userid == 0) {
			$result_arr['status'] = 0;
			$result_arr['message'] = '你未登录或已经过期了，新增的任务将不属于你私有，请先登录！';
		}

		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	public function shadow()
	{
		$newnode_sort = floor((microtime(true) - 1400000000));
		$this->load->database();

		//			$sql = "INSERT INTO task (title, parent,areaid,sort,in_date,uid) 
		//			VALUES (".$this->db->escape($_REQUEST['title']).", ".$this->db->escape($_REQUEST['parent']).", ".$this->db->escape($_REQUEST['areaid']).",'".$newnode_sort."','".date("Y-m-d H:m:s")."','". $this->_login_userid."')";
		//			$this->db->query($sql);

		$data = array(
			'title' => $_REQUEST['title'], //如果也用escap的话，插入到表的字符串会被加上引号
			'parent' => $_REQUEST['parent'],
			'internal_link' => $_REQUEST['source_id'],
			'sort' => $newnode_sort,
			'in_date' => date("Y-m-d H:m:s"),
			'uid' => $this->_login_userid
		);
		if (isset($_POST['simple'])) {
			$data['simple'] = 1; //如果是来自简单任务视图
		}
		if (isset($_POST['active'])) {
			$data['active'] = 1; //如果是来自简单任务视图
		}
		if (isset($_POST['areaid'])) {
			$data['areaid'] = $this->db->escape($_REQUEST['areaid']);
		}
		if (isset($_POST['team'])) {
			$data['tid'] = $_POST['team']; //如果是来自团队视图
		}
		$this->db->insert('task', $data);



		if ($this->db->affected_rows() > 0) {
			$status = 1;
			$newid = $this->db->insert_id();
			$sql = "call changeTaskParentAndParents(" . $newid . "," . $this->db->escape($_POST['parent']) . "," . $this->_login_userid . ");";
			$this->db->query($sql);
		} else {
			$status = 0;
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $this->db->last_query(),
			'data' => array(
				'newid' => $newid,
				'newnode_sort' => $newnode_sort
			)
		);

		if ($this->_login_userid == 0) {
			$result_arr['status'] = 0;
			$result_arr['message'] = '你未登录或已经过期了，新增的任务将不属于你私有，请先登录！';
		}

		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	// 改变父节点
	public function change_parent()
	{
		if (!isset($_POST['taskid']) || !isset($_POST['new_parent'])) {
			$result_arr['status'] = 'fail';
			$result_arr['message'] = '参数非法';
			$json_string = json_encode($result_arr);
			echo $json_string;
			return;
		}
		$this->load->database();

		//原只更新task的parent		
		/* 		$data = array(
               'parent' => $_POST['new_parent']
            );
		$this->db->where('id',$_POST['taskid']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data); */
		//调用存储过程，完成更新task的parent和parents，以及所有子任务的parents
		$sql = "call changeTaskParentAndParents(" . $_POST['taskid'] . "," . $_POST['new_parent'] . "," . $this->_login_userid . ");";
		$this->db->query($sql);

		$result_arr = array();
		if ($this->db->affected_rows() > 0) {
			$result_arr['status'] = 'success';
			$result_arr['message'] = '消息' . $this->db->last_query() . '影响行数：' . $this->db->affected_rows();
		} else {
			$result_arr['status'] = 'fail';
			$result_arr['message'] = '消息' . $this->db->last_query() . '影响行数：' . $this->db->affected_rows();
		}
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	// 修改任务标题
	public function edit()
	{
		$this->load->database();
		$data = array(
			'title' => $_POST['title']
		);
		$this->db->where('id', $_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		//		echo   $_POST['taskid'],' TO ',$_POST['new_parent'];
		//		echo $this->db->last_query();
		//		echo $this->db->affected_rows();
	}

	//修改注释，节点类型和链接
	public function editmore()
	{
		$this->load->database();
		$data = array(
			'comment' => $_POST['comment'],
			'nodetype' => $_POST['nodetype'],
			'link' => $_POST['link']
		);
		$this->db->where('id', $_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		//		echo   $_POST['taskid'],' TO ',$_POST['new_parent'];
		//		echo $this->db->last_query();
		//		echo $this->db->affected_rows();
	}


	public function change_stage()
	{
		$this->load->database();
		$data = array(
			'stage' => $_POST['stage']
		);
		$this->db->where('id', $_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
	}


	public function change()
	{
		$this->load->database();
		$data = array(
			$_POST['parm1'] => $_POST['value1']
		);
		$this->db->where('id', $_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		if ($this->db->affected_rows() > 0) {
			$status = 1;
		} else {
			$status = 0;
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $this->db->last_query()
		);
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	public function archive()
	{
		// if(!$value){
		// $value=1;
		// }else{
		// $value=0;
		// }
		$this->load->database();
		$data = array(
			'archive' => $_POST['archive']
		);
		$this->db->where('id IN (' . $_POST['tasklist'] . ')');
		//		$names = array($_POST['tasklist']);
		//		echo $names;
		//		$this->db->where_in('id', $names);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		if ($this->db->affected_rows() > 0) {
			$status = 1;
		} else {
			$status = 0;
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $this->db->last_query()
		);
		$json_string = json_encode($result_arr);
		echo $json_string;
	}


	public function changeSort2()
	{
		$this->load->database();
		$data = array(
			'sort' => $_POST['sort1']
		);
		$this->db->where('id', $_POST['id1']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		$query1 = $this->db->affected_rows();
		$message1 = "step1:" . $query1 . "," . $this->db->last_query();
		//		echo $message1;
		//		echo $query1;

		$data = array(
			'sort' => $_POST['sort2']
		);
		$this->db->where('id', $_POST['id2']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		$query2 = $this->db->affected_rows();
		$message2 = "step2:" . $query2 . "," . $this->db->last_query();
		//		echo $message2;
		//		echo $query2;

		if (($query1 + $query2) > 0) {
			$status = 1;
		} else {
			$status = 0;
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $message1 . $message2,
		);
		$json_string = json_encode($result_arr);
		echo $json_string;
	}


	public function set_parm_null()
	{
		$this->load->database();
		$sql = 'UPDATE task SET ' . $_POST['parm1'] . '=NULL WHERE id=' . $_POST['id'] . ';';
		//		echo $sql;
		$query = $this->db->query($sql);
		if ($this->db->affected_rows() > 0) {
			$status = 1;
		} else {
			$status = 0;
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $this->db->last_query()
		);
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	public function del()
	{
		$taskid = $_POST['id'];
		//       $teamid=$_POST['team'];
		if (isset($_POST['team'])) {
			if ($this->check_is_member($_POST['team'])) {
				$this->db->where('tid', $_POST['team']);
			} else {
				$this->db->where('tid', $_POST['team']);
				$this->db->where('uid', $this->_login_userid);
			}
		} else {
			$this->db->where('uid', $this->_login_userid);
			$this->db->where('tid IS NULL ', NULL, FALSE);
		}
		$this->load->database();
		$this->db->where('parent', $taskid);
		//        $this->db->where('uid', $this->_login_userid);
		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$result_arr = array(
				'status' => 0,
				'message' => '该节点还有子结点，或你没有权限，不能被删除!'
			);
		} else {
			$query->free_result();
			$sql = "DELETE FROM task WHERE id=" . $taskid . ";";
			$this->db->query($sql);
			if ($this->db->affected_rows() > 0) {
				$result_arr = array(
					'status' => 1,
					'message' => '已成功删除!'
				);
			} else {
				$result_arr = array(
					'status' => 0,
					'message' => '出错了：' . $this->db->last_query()
				);
			}
		}
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	// 取得任务的直接子节点
	public function getchild($parent = 0)
	{
		$this->load->database();
		$this->db->where('parent', $parent);
		$this->db->where('uid', $this->_login_userid);
		$this->db->order_by('sort', 'desc');
		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$rows_arr = array();
			foreach ($query->result_array() as $row) {
				//				echo $row['id'];
				$rows_arr[$row['id']] = $row;
			}
			// print_r($rows_arr);
			$json_string = json_encode($rows_arr);
			echo $json_string;
		}
	}


	public function change_task_and_childrens_area()
	{
		$taskid = $_POST['taskid'];
		$childlist = $this->get_all_child_list($taskid);

		$this->load->database();
		$data = array(
			'areaid' => $_POST['new_area'],
		);

		$this->db->where('uid', $this->_login_userid);
		$this->db->where(' FIND_IN_SET(id,"' . $childlist . '")>0 ', NULL, FALSE); //从子任务列表中取
		$this->db->update('task', $data);
		if ($this->db->affected_rows() > 0) {
			$sql_mess = $this->db->last_query();
			$this->db->close();
			$this->load->database();
			$data = array(
				'parent' => 2,
			);
			$this->db->where('id', $taskid);
			$this->db->where('uid', $this->_login_userid);
			$this->db->update('task', $data);
			if ($this->db->affected_rows() > 0) {
				$status = 1;
				$sql_mess .= $this->db->last_query();
			} else {
				$status = 0;
				$sql_mess .= $this->db->last_query();
			}
		} else {
			$status = 0;
			$sql_mess = $this->db->last_query();
		}
		$result_arr = array(
			'status' => $status,
			'message' => '消息' . $sql_mess
		);
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	// 取得active为1的任务
	public function active()
	{
		$this->load->database();
		$this->db->where('active', 1);
		$this->db->where('uid', $this->_login_userid);
		$this->db->order_by('sort', 'desc');
		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$rows_arr = array();
			foreach ($query->result_array() as $row) {
				//				echo $row['id'];
				$rows_arr[$row['id']] = $row;
			}
			//			print_r($rows_arr);
			$json_string = json_encode($rows_arr);
			echo $json_string;
		}
	}

	// 取得attention>0的任务
	public function get_attention()
	{
		$this->load->database();
		$this->db->where("attention > 0 ");
		$this->db->where('uid', $this->_login_userid);
		$this->db->order_by('attention', 'desc');
		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$rows_arr = array();
			foreach ($query->result_array() as $row) {
				//				echo $row['id'];
				$rows_arr[$row['id']] = $row;
			}
			//			print_r($rows_arr);
			$json_string = json_encode($rows_arr);
			echo $json_string;
		}
	}

	// 根据id取得某个节点，非sys
	public function getnode($id, $sys = 0)
	{
		$this->load->database();
		$this->db->where('id', $id);
		//		$this->db->where('uid', $this->_login_userid);
		$query1 = $this->db->get('task');


		if ($query1->num_rows() > 0) {
			$row = $query1->row_array();
			$query1->free_result();
			//			print_r($row);
			if ($row['nodetype'] == 'S') {
				$query = $this->db->get('task');
				$where = '';
				if ($row['tags']) {
					$tags = explode(' ', trim($row['tags']));
					foreach ($tags as $tag) {
						if ($tag) {
							$where .= ' AND (tags LIKE "%' . $tag . '%" OR title LIKE "%' . $tag . '%") ';
						}
					}
				}
				if ($row['stage']) {
					$where .= ' AND stage="' . $row['stage'] . '" ';
				}
				if ($where) {
					$where = '1 AND id<>' . $row['id'] . $where;
				} else {
					return; //防止出现空查询条件
				}
				//				echo $where;

				$this->db->where($where, NULL, FALSE);
				$getway = "S";
			} else {
				$this->db->where('parent', $id); //默认查询该ID的子节点
				$getway = 'P'; //记录节点取得的方式
			}
		}
		if ($sys == 1) {
			$this->db->where('uid', 3);
		} else {
			$this->db->where('uid', $this->_login_userid);
		}

		$this->db->order_by('sort desc,in_date desc');
		$query2 = $this->db->get('task');
		if ($query2->num_rows() > 0) {
			$rows_arr = array();
			foreach ($query2->result_array() as $row) {
				//				$rows_arr[$row['id']]=$row;
				$row['getway'] = $getway;
				$rows_arr[] = $row;
			}
			$json_string = json_encode($rows_arr);
			echo $json_string;
		}
	}

	// 根据id取得某个节点
	public function getnode_sys($id)
	{
		$this->getnode($id, 1);
	}

	//提供where子句查询节点
	private function get_by_where($where)
	{
		$this->load->database();
		if ($where) {
		} else { //防止出现空查询条件
			$row[id] = "10";
			$row['title'] = "出错了，不能进行空查询！";
			$rows_arr[] = $row;
			$json_string = json_encode($rows_arr);
			echo $json_string;
		}
		//		echo $where;		
		$this->db->where('uid', $this->_login_userid);
		$this->db->where($where, NULL, FALSE);
		$getway = "S"; //记录节点取得的方式
		$this->db->order_by('sort', 'desc');
		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$rows_arr = array();
			foreach ($query->result_array() as $row) {
				//				$rows_arr[$row['id']]=$row;
				$row['getway'] = $getway;
				$rows_arr[] = $row;
			}
			$json_string = json_encode($rows_arr);
			echo $json_string;
		}
	}

	public function search_by_post_parm()
	{
		$where = " 1 ";
		if ($_REQUEST['active']) {
			$where .= " AND active=" . $this->db->escape($_REQUEST['active']) . " ";
		}
		if ($_REQUEST['parent']) {
			$where .= " AND parent=" . $this->db->escape($_REQUEST['parent']) . " ";
		}
		if ($_REQUEST['stage'] === null) {
		} else {
			$where .= " AND stage=" . $this->db->escape($_REQUEST['stage']) . " ";
		}
		//		echo $where;
		$this->get_by_where($where);
	}

	// 根据stage状态查询查询
	public function search_by_stage($stage)
	{
		//		$where=" stage='".$stage."' ";
		$where = " active=1 AND stage='" . $stage . "' ";
		$this->get_by_where($where);
	}

	public function search_by_text()
	{
		$result_arr = array();
		$this->load->database();
		$where = '';
		$search_words = explode(' ', trim($_POST['search_words']));
		foreach ($search_words as $word) {
			if ($word) {
				$where .= ' AND (tags LIKE "%' . $word . '%" OR title LIKE "%' . $word . '%") ';
			}
		}
		if ($where) {
			$where = '1' . $where;
		} else {
			$result_arr['status'] = 'error';
			$result_arr['message'] = '不能执行一个空查询！';
			$json_string = json_encode($result_arr);
			echo $json_string;
			return; //防止出现空查询条件
		}
		//根据是否在团队模式下还是普通登录用户模式下搜索，设置不同的条件
		if (isset($_POST['team'])) {
			if ($this->check_is_member($_POST['team'])) {
				$this->db->where('tid', $_POST['team']);
			} else {
				$this->db->where('tid', $_POST['team']);
				$this->db->where('uid', $this->_login_userid);
			}
		} else {
			$this->db->where('uid', $this->_login_userid);
			$this->db->where('tid IS NULL ', NULL, FALSE);
		}

		$this->db->where($where, NULL, FALSE);
		$getway = "S"; //记录节点取得的方式
		$this->db->order_by('sort', 'desc');
		$query = $this->db->get('task');
		if (($num_rows = $query->num_rows()) > 0) {
			$rows_arr = array();
			foreach ($query->result_array() as $row) {
				//				$rows_arr[$row['id']]=$row;
				$row['getway'] = $getway;
				$rows_arr[] = $row;
			}
			$result_arr['data'] = $rows_arr;
			$result_arr['status'] = 'success';
			$result_arr['message'] = '共找到' . $num_rows . '个结果。';
		} else {
			$result_arr['status'] = 'noresult';
			$result_arr['message'] = '没有匹配的结果！';
		}
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	public function get($id)
	{
		$this->load->database();
		$this->db->where('id', $id);
		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$row = $query->row_array();
			$json_string = json_encode($row);
			echo $json_string;
		}
		//		print_r($row);
	}
	private function get_parents_array($id)
	{
		$this->load->database();
		$parents_array = array();
		$opt = $id;
		do {
			$this->db->where('id', $opt);
			$query = $this->db->get('task');
			//			echo $this->db->last_query();
			if ($query->num_rows() > 0) {
				$row = $query->row_array();
				//				$result_message=var_export($row,true);
				$parents_array[] = $row['id'];
				$opt = $row['parent'];
				continue;
			} else {
				$opt = NULL;
				break;
			}
		} while ($opt);
		return array_reverse($parents_array);
	}

	//取得最后更新的的任务
	public function getlastedit()
	{
		$this->load->database();
		if ($this->_login_userid) {
			$this->db->where('uid', $this->_login_userid);
		} else {
			$this->db->where('uid', 5);
		}
		$where = "lastupdate > DATE_SUB( NOW(),INTERVAL 1 MINUTE)";
		$this->db->where($where, NULL, FALSE);
		//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
		//		$this->db->where('archive !=', '1');//默认只取得所有未归档的任务
		$this->db->order_by('parent asc,sort desc');
		$query = $this->db->get('task');
		if ($num_rows = $query->num_rows() > 0) {
			//			$result_array['message']=$result_message;
			$result_array['data'] = $query->result_array();
			$this->array_to_json($result_array);
		}
	}



	//依据任务的tags内容中含关键词来查询
	public function getparents_by_tag()
	{
		$all = array();
		$this->load->database();
		$where = '';
		$search_words = explode(' ', trim($_POST['search_words']));
		// $search_words=explode(' ', trim('默认打开'));
		foreach ($search_words as $word) {
			if ($word) {
				$where .= ' AND (tags LIKE "%' . $word . '%") ';
			}
		}
		if ($where) {
			$where = '1' . $where;
		} else {

			return; //防止出现空查询条件
		}
		//		echo $where;		
		$this->db->where('uid', $this->_login_userid);
		$this->db->where($where, NULL, FALSE);
		$getway = "S"; //记录节点取得的方式

		$query = $this->db->get('task');
		if ($query->num_rows() > 0) {
			$rows_arr = array();
			$rows_arr = $query->result_array();
			foreach ($rows_arr as $row) {
				$all = array_merge($all, $this->get_parents_array($row['id']));
			}
			$all = array_unique($all);
			$json_string = json_encode($all);
			echo $json_string;
		}
	}
}
